/*
 * ebc_con.c - EBC - connect, close
 * Clunix, KyungWoon Cho, cezanne@clunix.com, 2006.1
 *
 * Copyright (c) 2001-2008 by Clunix Inc. All Rights Reserved.
 */

#include "config.h"

#include "ebc_p.h"

srt_t	ST_IP;
srt_t	ST_NDID;
srt_t	ST_MDID;
srt_t	ST_PTID;
srt_t	ST_RES_NDID;
srt_t	ST_BDCAST_RES;

ECMBOOL
ebc_get_result_ndid(sr_t *sr_res_ndid, ebc_ndid_t *pndid)
{
	if (!sr_get_type(sr_res_ndid) == ST_RES_NDID)
		return ECM_FALSE;
	if (pndid)
		*pndid = sr_geti_int(sr_res_ndid, 0);
	return ECM_TRUE;
}

ECMBOOL
ebc_get_result_sr(sr_t *sr_res_ndid, sr_t **psr)
{
	if (!sr_get_type(sr_res_ndid) == ST_RES_NDID)
		return ECM_FALSE;
	if (psr)
		*psr = sr_geti(sr_res_ndid, 1);
	return ECM_TRUE;
}

static int
srt_ip_print(srt_t srt, char *buf, ecm_size_t *pbuflen, sr_val_t srv)
{
	ecm_size_t	len;
	struct in_addr	inaddr;
	const char	*ipstr;

        /* TODO: This is not thread-safe */

        inaddr.s_addr = srv.ival;
	ipstr = ecm_strdup(inet_ntoa(inaddr));
	len = ecm_strlen(ipstr);
	if (*pbuflen < len) {
		*pbuflen = len;
		ecm_free(ipstr);
		return -1;
	}

	memcpy(buf, ipstr, len);
	ecm_free(ipstr);
        return len;
}

static ECMBOOL
srt_ip_scan(srt_t srt, char *asrv, sr_val_t *psrv)
{
	struct in_addr	inaddr;

	if (!ecm_aton(asrv, &inaddr))
		return ECM_FALSE;
	psrv->ival = inaddr.s_addr;
	return ECM_TRUE;
}

static sr_parser_t	ip_parser = {
	srt_ip_print, srt_ip_scan
};

static void
ebc_init_types(void)
{
	ST_IP = sr_type_add(SR_BT_INT, "ip", NULL, &ip_parser);
	ST_NDID = sr_type_add(SR_BT_INT, "ndid", NULL, NULL);
	ST_MDID = sr_type_add(SR_BT_INT, "mdid", NULL, NULL);
	ST_PTID = sr_type_add(SR_BT_INT, "ptid", NULL, NULL);
	ST_RES_NDID = sr_type_add(SR_BT_DIR, "res_ndid", NULL, NULL);
	ST_BDCAST_RES = sr_type_add(SR_BT_DIR, "bdcast_res", NULL, NULL);
}

extern void ebc_init_pktb(void);
extern void ebc_init_cb(void);
extern void ebc_setup_default_port(void);

ECMBOOL
ebc_initialize(void)
{
	static ECMBOOL	initialized = ECM_FALSE;

	if (initialized)
		return ECM_TRUE;

	if (!ecm_initialize())
		return ECM_FALSE;
	ebc_pch_initialize();
	ebc_init_types();
	ebc_init_pktb();
	ebc_init_cb();
	ebc_setup_default_port();
	initialized = ECM_TRUE;
	return ECM_TRUE;
}
